<?php

namespace org;

use think\facade\Config;
use think\facade\Env;
use think\facade\Route;

/**
 * 系统配置文件操作类
 * Class ConfigHelper
 * @package org
 */
class ConfigHelper {
    /**
     * 获取配置参数
     */
    public function getConfig($name) {
        $config = Config::get($name . '.');
        return $config;
    }

    /**
     * 设置参数
     * @param $name
     */
    public function setConfig($name, $arr) {
        $path = Env::get('CONFIG_PATH') . $name . '.php';
        $arr = arr2export($arr);
        $content = <<<EOT
<?php
return $arr;
EOT;
        if (false === file_put_contents($path, $content)) {
            exception('写入配置文件失败！', 40001);
        }
        return true;
    }

    /**
     * 获取home模块路由规则
     */
    public function getHomeRoute() {
        $rootDomain = request()->rootDomain();
        $ruleList = Route::getRuleList($rootDomain);
        $homeRule = [];
        if(empty($ruleList)) return $homeRule;
        foreach ($ruleList as $v) {
            if (is_string($v['route']) && strpos($v['route'], 'home/') !== false) {
                $homeRule[] = $v;
            }
        }
        return $homeRule;
    }

    /**
     * 设置home模块规则
     * @param $items 规则列表
     */
    public function setHomeRoute($items) {
        $data = [];
        if(!empty($items)){
            //重新组装需要数据
            foreach ($items as $v) {
                if (!empty($v['rule']) && !empty($v['route'])) {
                    if (!empty($v['name'])) {
                        $data[] = "Route::rule('{$v['rule']}','{$v['route']}')->name('{$v['name']}');";
                    } else {
                        $data[] = "Route::rule('{$v['rule']}','{$v['route']}');";
                    }
                }
            }
            $content = '<?php' . PHP_EOL . implode(PHP_EOL, $data);
        }else{
            $content = '<?php' . PHP_EOL . 'return [];';
        }
        $path = Env::get('ROOT_PATH') . 'route/home.php';

        if (false === file_put_contents($path, $content)) {
            exception('写入配置文件失败！', 40001);
        }
        return true;
    }
}